package com.raincat.tools.multimediapickertools;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.raincat.tools.R;
import com.raincat.tools.multimediapickertools.utils.ImageCacheUtils;
import com.raincat.tools.multimediapickertools.utils.LazyLoadFragment;
import com.raincat.tools.multimediapickertools.utils.MultiMediaItem;
import com.raincat.tools.multimediapickertools.utils.PickerTextureView;

/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2019/02/27
 *     desc   : 视频预览
 *     version: 1.0
 * </pre>
 */

public class VideoBrowseFragment extends LazyLoadFragment {
    private Context context;
    private static final String BUNDLE_URI = "uri";

    private View rootView;
    private RelativeLayout rela_root;
    private PickerTextureView textureView;
    private ImageView iv_thumb, iv_play;

    private MultiMediaItem multiMediaItem;
    private MediaPlayer mediaPlayer;
    private Surface surface;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (multiMediaItem == null && savedInstanceState.containsKey(BUNDLE_URI)) {
                multiMediaItem = (MultiMediaItem) savedInstanceState.getSerializable(BUNDLE_URI);
            }
        }
        rootView = inflater.inflate(R.layout.picker_fragment_videosbrowse, container, false);
        iv_thumb = rootView.findViewById(R.id.iv_thumb);
        iv_play = rootView.findViewById(R.id.iv_play);
        textureView = rootView.findViewById(R.id.textureView);
        rela_root = rootView.findViewById(R.id.rela_root);

        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
                surface = new Surface(surfaceTexture);
                iv_thumb.setVisibility(View.VISIBLE);
                iv_play.setVisibility(View.VISIBLE);
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
                try {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                    surface = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

            }
        });

        setVideoRatio(multiMediaItem.path);
        Glide.with(context).asBitmap().load(getVideoThumb(multiMediaItem.path)).dontAnimate().into(iv_thumb);
        listener();
        return rootView;
    }

    void setMultiMediaItem(MultiMediaItem multiMediaItem) {
        this.multiMediaItem = multiMediaItem;
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible) {
            iv_play.setVisibility(View.VISIBLE);
            iv_thumb.setVisibility(View.VISIBLE);
        } else {
            try {
                surface = null;
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void listener() {
        iv_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new PlayVideo().start();
            }
        });
    }

    @Override
    protected void onFragmentFirstVisible() {
    }

    private class PlayVideo extends Thread {
        @Override
        public void run() {
            try {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(multiMediaItem.path);
                mediaPlayer.setSurface(surface);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        iv_play.setVisibility(View.GONE);
                        iv_thumb.setVisibility(View.GONE);
                        mediaPlayer.start();
                    }
                });
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.reset();
                        iv_play.setVisibility(View.VISIBLE);
                        iv_thumb.setVisibility(View.VISIBLE);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 截取视频第一帧
     *
     * @param path 地址
     * @return
     */
    private String getVideoThumb(String path) {
        ImageCacheUtils imageCacheUtils = new ImageCacheUtils(context);
        if (imageCacheUtils.getCachePath(path) == null) {
            MediaMetadataRetriever media = new MediaMetadataRetriever();
            media.setDataSource(path);
            Bitmap bm = media.getFrameAtTime();
            imageCacheUtils.addBitmapToFile(path, 70, bm);
        }
        return imageCacheUtils.getCachePath(path);
    }

    /**
     * 获取视频宽高和旋转角度
     *
     * @param path
     */
//    private void setVideoRatio(String path) {
//        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
//        mediaMetadataRetriever.setDataSource(path);
//        String heightString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
//        String widthString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
//        String rotationString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
//        if (heightString != null && widthString != null && rotationString != null) {
//            float videoHeight, videoWidth;
//            int videoRotation = Integer.valueOf(rotationString);
//            if (videoRotation == 0 || videoRotation == 180) {
//                videoHeight = Float.valueOf(heightString);
//                videoWidth = Float.valueOf(widthString);
//            } else {
//                videoWidth = Float.valueOf(heightString);
//                videoHeight = Float.valueOf(widthString);
//            }
//            int imageWidth = getPhoneW(), imageHeight = (int) (videoHeight * 1.0f / videoWidth * imageWidth);
//            if (imageHeight > getPhoneH()) {
//                imageHeight = getPhoneH();
//                imageWidth = (int) (videoWidth * 1.0f / videoHeight * imageHeight);
//            }
//            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(imageWidth, imageHeight);
//            rela_root.setLayoutParams(layoutParams);

//            textureView.setRotation(videoRotation);
//            textureView.setVideoSize(Integer.valueOf(widthString), Integer.valueOf(heightString));

//            if (videoRotation == 90 || videoRotation == 270) {
//                textureView.setScaleX(imageHeight * 1.0f / imageWidth);
//                textureView.setScaleY(imageWidth * 1.0f / imageHeight);
//            }
//            textureView.setRotation(videoRotation);
//        }
//    }

    /**
     * 获取视频宽高和旋转角度
     *
     * @param path
     */
    private void setVideoRatio(final String path) {
        rootView.post(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                mediaMetadataRetriever.setDataSource(path);
                String heightString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
                String widthString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
                String rotationString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
                if (heightString != null && widthString != null && rotationString != null) {
                    float videoHeight, videoWidth;
                    int videoRotation = Integer.parseInt(rotationString);
                    if (videoRotation == 0 || videoRotation == 180) {
                        videoHeight = Float.parseFloat(heightString);
                        videoWidth = Float.parseFloat(widthString);
                    } else {
                        videoWidth = Float.parseFloat(heightString);
                        videoHeight = Float.parseFloat(widthString);
                    }
                    int imageWidth = rootView.getWidth(), imageHeight = (int) (videoHeight * 1.0f / videoWidth * imageWidth);
                    if (imageHeight > rootView.getHeight()) {
                        imageHeight = rootView.getHeight();
                        imageWidth = (int) (videoWidth * 1.0f / videoHeight * imageHeight);
                    }
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(imageWidth, imageHeight);
                    rela_root.setLayoutParams(layoutParams);

//                    textureView.setRotation(videoRotation);
//                    textureView.setVideoSize(Integer.valueOf(widthString), Integer.valueOf(heightString));
//
//                    if (videoRotation == 90 || videoRotation == 270) {
//                        textureView.setScaleX(imageHeight * 1.0f / imageWidth);
//                        textureView.setScaleY(imageWidth * 1.0f / imageHeight);
//                    }
//                    textureView.setRotation(videoRotation);
                }
            }
        });
    }

//    private int getPhoneW() {
//        DisplayMetrics displayMetrics = new DisplayMetrics();
//        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//        return displayMetrics.widthPixels;
//    }
//
//    private int getPhoneH() {
//        DisplayMetrics displayMetrics = new DisplayMetrics();
//        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//        return displayMetrics.heightPixels;
//    }

    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        multiMediaItem = null;
        super.onDestroyView();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        View rootView = getView();
        if (rootView != null) {
            outState.putSerializable(BUNDLE_URI, multiMediaItem);
        }
    }
}
